import React, { createRef } from 'react'
import { Table, Input, Button, InputNumber, message, Row, Col, Select } from 'antd'
import apis from '@/apis/SystemSettings'
import comApis from '@/apis'
import { columnRenders, http } from '@/lib'
import UdSelect from '@/components/UdFormControls/UdSelect'
import dayjs from 'dayjs'

interface IProps {}
interface IState {
  dataSource: any[]
  editArr: any[]
  loading: boolean
  yearList: any[]
  checkedYear: any
}
export default class EditTable extends React.Component<IProps, IState> {
  state: IState = {
    checkedYear: dayjs().year() + '',
    loading: false,
    dataSource: [],
    editArr: [],
    yearList: [],
  }
  componentDidMount() {
    this.getAllStatistics()
    this.getYearList()
  }

  private getAllStatistics = (value: string = this.state.checkedYear) => {
    this.setState({ loading: true, editArr: [] })
    let params = { statiYear: value }
    http
      .post(apis.queryAllStatistics, params)
      .then(res => {
        let { data } = res
        this.setState({ dataSource: data })
      })
      .finally(() => {
        this.setState({ loading: false })
      })
  }

  private handUpdateStatistics = record => {
    http.post(apis.updateStatistics, record).then(res => {
      message.success('操作成功')
      this.getAllStatistics()
    })
  }

  private renderInput = (text, record, index, field) => {
    const { editArr } = this.state
    if (record.edit) {
      return (
        <InputNumber
          style={{ width: '100%' }}
          value={editArr[index] && editArr[index][field] ? editArr[index][field] : record[field]}
          min={0}
          formatter={value => {
            const reg = /^(-)*(\d+)\.(\d\d).*$/
            const val = String(value).replace(reg, '$1$2.$3')
            return val
          }}
          parser={value => {
            const reg = /^(-)*(\d+)\.(\d\d).*$/
            const val = String(value).replace(reg, '$1$2.$3')
            return val
          }}
          onChange={value => this.inputChange(value, record, index, field)}
        />
      )
    } else {
      return text
    }
  }

  private edit = record => {
    const { dataSource, editArr } = this.state
    const newArr = [...dataSource]
    const newEditArr = [...editArr]
    const inx = newArr.findIndex(item => item.id === record.id)
    newArr.splice(inx, 1, { ...record, edit: true })
    newEditArr[inx] = { ...record }
    this.setState({ dataSource: newArr, editArr: newEditArr })
  }

  private inputChange = (value, record, index, field) => {
    let { editArr } = this.state
    const newRecord = { ...record }
    newRecord[field] = value
    if (editArr[index]) {
      editArr[index][field] = value
    } else {
      editArr[index] = { ...newRecord }
    }
    this.setState({ editArr })
  }

  private handleSave = (record, index) => {
    const { editArr } = this.state
    this.handUpdateStatistics(editArr[index])
  }

  private handCancel = record => {
    const { dataSource, editArr } = this.state
    const newArr = [...dataSource]
    const newEditArr = [...editArr]
    const index = newArr.findIndex(item => item.id === record.id)
    newArr.splice(index, 1, { ...newArr[index], edit: false })
    newEditArr.splice(index, 1)
    this.setState({ dataSource: newArr, editArr: newEditArr })
  }

  private getYearList = () => {
    http.get(comApis.GetQuotaAssessYearList).then(res => {
      const yearList = res.data?.map(({ year: value, name: title }) => ({ value: value + '', title })) || []
      this.setState({ yearList })
    })
  }

  render() {
    const { loading, yearList } = this.state
    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        render: (text, record, index) => index + 1,
      },
      {
        title: '年份',
        dataIndex: 'statiYear',
      },
      {
        title: '月份',
        dataIndex: 'statiMonth',
      },
      {
        title: '倍数值',
        dataIndex: 'statiCoefficient',
        render: (text, record, index) => this.renderInput(text, record, index, 'statiCoefficient'),
      },
      {
        title: '操作',
        key: 'edit',
        width: '120px',
        render: columnRenders.operate([
          {
            title: '编辑',
            action: (text, record, index) => {
              this.edit(record)
            },
            show: (text, record, index) => {
              return !!!record.edit
            },
          },
          {
            title: '保存',
            action: (text, record, index) => {
              this.handleSave(record, index)
            },
            show: (text, record, index) => {
              return !!record.edit
            },
          },
          {
            title: '取消',
            action: (text, record, index) => {
              this.handCancel(record)
            },
            show: (text, record, index) => {
              return !!record.edit
            },
          },
        ]),
      },
    ]

    return (
      <div>
        <Row type="flex" justify="start" align="middle" style={{ marginBottom: '20px' }}>
          <Col span={1}>年份：</Col>
          <Col span={5}>
            <UdSelect
              defaultValue={dayjs().year() + ''}
              options={yearList}
              allowClear={false}
              showSearch={true}
              optionFilterProp="children"
              style={{ width: '100%' }}
              onChange={value => {
                this.setState({ checkedYear: value }, () => {
                  this.getAllStatistics()
                })
              }}
            />
          </Col>
        </Row>
        <Table
          loading={loading}
          rowKey={record => record.id}
          dataSource={this.state.dataSource}
          columns={columns}
          pagination={false}
        />
      </div>
    )
  }
}
